<?php
/**
 * Created by PhpStorm.
 * User: huqi
 * Date: 17/6/28
 * Time: PM4:24
 */

namespace App\traits;


trait RbacTrait
{
    function mathRules($path,$method,$rules){
        foreach ($rules as $rule){

            if(is_string($rule)){
                $rule = ['uri' => $rule , 'method' => ''] ;
            }

            $uri = $rule['uri'] ;
            $uri = trim($uri) ;
            if(empty($uri)){
                continue ;
            }

            // 验证method
            $ruleMethod = trim($rule['method']) ;
            if(!empty($ruleMethod)){
                $ruleMethod = strtoupper($ruleMethod) ;
                $methods = explode('|',$ruleMethod) ;
                // 如果方法不匹配 直接跳过
                if(!in_array(strtoupper($method),$methods)){
                    continue ;
                }
            }

            $len = strlen($uri) ;
            if($uri[$len - 1] == '*'){
                // 前缀匹配
                $prefixPos = $len - 1 ;
                if(substr($path,0,$prefixPos) == substr($uri,0,$prefixPos)){
                    return true ;
                }
            }else{
                // 用等号匹配
                if($uri == $path){
                    return true ;
                }
            }
        }
        return false ;
    }
}